<?php
/**
 * Author: LaiGuiming
 * Time: 2017-08-30 18:01
 * Copyright (C) 2016 Longyan Wehome Message CO.,LTD.
 */
namespace app\admin\lib\traits;

/**
 * 后台增删改成基本方法
 * Trait Backend
 * @package app\admin\lib\traits
 */
trait Crud
{
    /**
     * 列表
     * @return mixed
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 获取分页数据
     * @param int $limit
     * @param int $offset
     */
    public function loadData($limit = 10,$offset=0)
    {
        $where="status!=2";
        $where=$this->getCondition($where,"name","like");
        $counts=$this->model->where($where)->count();
        $data=$this->model->where($where)->order('ct desc')->limit($offset,$limit)->select();
        $res = array("rows" => $data, "total" => $counts);
        echo json_encode($res);
    }

    /**
     * 新增
     * @param int $id
     * @return mixed
     */
    public function add($id = -1)
    {
        $this->assign('data', $this->model->get($id));
        return $this->fetch();
    }

    /**
     * 保存
     * @param string $id
     * @return string|void
     */
    public function save($id = '')
    {
        //校验
        $validate=validate($this->modelName);
        if(!$validate->check($_POST)){
            $this->resError($validate->getError());
            return;
        }

        if ($id != '') {
            $res = $this->model->allowField(true)->save($_POST,['id' => $id]);
            $this->saveLog("修改".$this->explain."【".$id."】");
        }else{
            $res = $this->model->allowField(true)->save($_POST);
            $this->saveLog("新增".$this->explain."【".$this->model->id."】");
        }
        $this->resData($res);
    }

    /**
     * 删除
     * @param string $id
     */
    public function del($id = '')
    {
        $this->model->where('id in ('.$id.')')->update([ 'status' => 2]);
        $this->saveLog("删除".$this->explain."【".$id."】");
        $this->resSuccess();
    }
}